import Vue from 'vue';
import Vuex from 'vuex';
import {Url} from "../utils/config";
import {get} from '../utils/request';

Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        token: localStorage.getItem('access_token'),
        user: localStorage.getItem('user'),
        stock_value: 5000,
        help:"",
        // profile:null
    },
    mutations: {
        updateToken(state, payload) {
            state.token = payload.token
            if (state.token) {
                localStorage.setItem('access_token', state.token)
            } else {
                localStorage.removeItem('access_token')
            }
        },

        updateStockValue(state, payload) {
            state.stock_value = payload.stock_value
            state.help = payload.help
        },
        updateUser(state, payload) {
            state.user = payload.user;
            if (state.user) {
                localStorage.setItem('user', state.user)
            } else {
                localStorage.removeItem('user')
            }
        },
        clearToken(state, payload) {
            state.token = null
            localStorage.removeItem('access_token')
        }
    },
    actions: {
        logout(ctx) {
            ctx.commit('clearToken')
            ctx.commit('updateUser', {user: null})
        },
        loadProfile(ctx) {
            if (ctx.state.token) {
                get(Url.profile).then((res) => {
                    let user = res.data.user;
                    if (user) {
                        ctx.commit('updateUser', {user: user})
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        }
    }
});
export default store